﻿using System.Linq;
using System.Web.Mvc;
using AutoClub.Core.Domain;
using AutoClub.Core.Domain.Dao;
using AutoClub.Models;

namespace AutoClub.Controllers
{
    public class RaceController : Controller
    {
        public IRaceRepo RacesDao { get; private set; }
        public ICarCategoriesRepo CarCategoriesDao { get; private set; }
        public IModelMapper ModelMapper { get; set; }
        public IUnitOfWork UoW { get; set; }

        public RaceController(IUnitOfWork uow, ICarCategoriesRepo carCategoriesDao, IRaceRepo raceDao, IModelMapper modelMapper)
        {
            this.CarCategoriesDao = carCategoriesDao;
            this.ModelMapper = modelMapper;
            this.RacesDao = raceDao;
            this.UoW = uow;
        }
        //
        // GET: /Race/

        public ActionResult Index()
        {
            return View();
        }

        // GET: /Race/Add
        public ActionResult Add()
        {
            var categories = this.CarCategoriesDao.GetAll();
            AddRaceModel model = new AddRaceModel(categories);

            return View(model);
        }


        // POST: /Race/Add
        [HttpPost]
        public ActionResult Add(AddRaceModel model)
        {
            Race instance = this.ModelMapper.Map<AddRaceModel, Race>(model);
            var categories = this.CarCategoriesDao.GetAll(); // TO DO : Cachear esto
            var states = this.RacesDao.GetAllRaceStates();// TO DO : Cachear esto

            instance.Category = categories.Single(c => c.Id.Equals(model.SelectedCategory));
            instance.State = states.Single(s => s.Value.Equals(RaceStateEnum.Opened));

            this.RacesDao.Add(instance);
            this.UoW.Commit();

            return RedirectToAction("Index", "Home");
        }

        // GET: /Race/ChangeStatus
        public ActionResult ChangeStatus()
        {
            var races = this.RacesDao.GetAll().Where(r => r.State.Value != RaceStateEnum.Closed).ToList();
            return View(races);

        }
    }
}
